package com.liu.manag.mq.consumer;

import com.liu.manag.common.Constant;
import com.liu.manag.config.RabbitConfig;
import com.liu.manag.entity.MsgLog;
import com.liu.manag.mq.MessageHelper;
import com.liu.manag.pojo.Mail;
import com.liu.manag.service.MsgLogService;
import com.liu.manag.utils.MailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class MailConsumer {

    @Autowired
    private MsgLogService msgLogService;

    @Autowired
    private MailUtil mailUtil;


    @RabbitListener(queues = RabbitConfig.MAIL_QUEUE_NAME)
    public void consumeMail(Message message, Channel channel) throws IOException {
        Mail mail = MessageHelper.messageToObject(message,Mail.class) ;
        log.info("收到消息:{}",mail.toString());

        String messageId = mail.getMsgId();
        MsgLog msgLog = msgLogService.queryById(messageId);
        if(null == msgLog || msgLog.getStatus().equals(Constant.MsgLogStatus.CONSUMED_SUCCESS)){
            log.info("重复消费,megId:{}",messageId);
            return ;
        }

        MessageProperties properties = message.getMessageProperties();
        long tag = properties.getDeliveryTag();
        boolean success = mailUtil.send(mail);
        if(success){

            msgLog.setStatus(Constant.MsgLogStatus.CONSUMED_SUCCESS);
            msgLogService.update(msgLog);
            channel.basicAck(tag,false);
        }else {
            channel.basicNack(tag,false,true);
        }
    }
}
